const baseUrl = 'http://zygq.opo5.com/api/';
const domainAddress = 'http://zygq.opo5.com/api';
const shopUrl = 'http://zygq.opo5.com/api/';
const uploadImage = 'http://zygq.opo5.com/api/common/upload';
// const baseUrl = 'http://zyapp.zywiny.com/api/';
// const domainAddress='http://zyapp.zywiny.com';
// const shopUrl='http://zyapp.zywiny.com/shop/';
// const uploadImage='http://zyapp.zywiny.com/uploadsImages';
/*const baseUrl = 'http://127.0.0.1:75/api/';
const domainAddress='http://127.0.0.1:75';
const shopUrl='http://127.0.0.1:75/shop/';
const uploadImage='http://127.0.0.1:75/uploadsImages';*/

const payUrl = '';
import custom from './custom.js';
import CryptoJS from 'crypto-js'

let isLoginFlag = false;

function guid() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}
/**
 * 获取token
 * @param {Object} callback:回调函数
 */
function getToken(callback) {
	const time = parseInt(new Date().getTime() / 1000)
	try {
		let token = uni.getStorageSync('x-api-token');
		token = typeof token == "undefined" || token == null ? '' : token;
		if (typeof callback == "function") {
			callback(token, time);
		} else {
			return token;
		}
	} catch (e) {
		uni.getStorage({
			key: 'x-api-token',
			success: function(res) {
				let token = res.data;
				token = typeof token == "undefined" || token == null ? '' : token;
				if (typeof callback == "function") {
					callback(token, time);
				}
			},
			fail() {
				if (typeof callback == "function") {
					callback('', time);
				}
			}
		});
	}
	// });

}

/**
 * 检查是否已经登录
 * @param {Object} callback
 */
function isLogin(isJump, callback) {
	getToken(function(token) {


		if (token == '' || !token) {
			custom.tool.jump(2, 'login/login');
		} else {
			callback(true);
		}

	});
}

/**
 * 发送请求
 * @param {Object} uri 请求地址
 * @param {Object} data 请求数据
 * @param {Object} callback 回调函数
 * @param {Object} method 请求方式
 * @param {Object} errorText 请求失败时提示
 */
function requests(uri, data, callback, method, errorText, isLoading) {
	isLoading = typeof isLoading != "boolean" ? false : isLoading;
	data = typeof data != "object" ? {} : data;
	method = typeof method != "string" ? 'GET' : method;
	errorText = typeof errorText != "string" ? '' : errorText;
	getToken(function(token, time) {
		let isLogin = uni.getStorageSync('isLogin');
		isLogin = typeof isLogin == "undefined" || isLogin == null ? '' : isLogin;
		if ((uri != 'common/webSetting') && (!token && isLogin) ) {
			custom.tool.jump(2, 'login/login');
			return
		}
		var key = '1062ce83a454d50e5d2c2a73c86fb978' + '@' + time
		const tempData = {}
		Object.keys(data).sort().map(item => {
			tempData[item] = data[item]
		})
		const newObj = []
		Object.keys(tempData).sort().map(item => {
			newObj.push(`${item}=${data[item]}`)
		})
		const signData = newObj.join('&')
		// console.log(signData)
		// console.log(key)
		var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
		hmac.update(signData);
		// const sha = CryptoJS.HmacSHA256(signData, key);
		// const sign = CryptoJS.createHmac('sha256', signData).update(key).digest('hex')
		// const sign = CryptoJS.enc.Hex.stringify(sha)
		// const sign1 = CryptoJS.enc.Base64.stringify(sha)
		const sign = CryptoJS.enc.Hex.stringify(hmac.finalize())
		// console.log(sign)
		// console.log(sign1)
		let header = {
			'token': token,
			'time': time,
			'sign': sign,
			'Content-Type': 'application/x-www-form-urlencoded'
		};
		// console.log(header)	
		console.log(data)
		console.log(baseUrl + uri, data)
		if (isLoading) {
			custom.tool.showLoading();
		}
		uni.request({
			url: baseUrl + uri,
			data: data,
			method: method,
			header: header,
			success: (res) => {
				custom.tool.hideLoading();
				//判断结果是否是正常的对象
				// if (typeof res != "object" || typeof res.data != "object") {
				// 	if (typeof errorText == "string" && errorText != '') {
				// 		custom.tool.showToast(errorText);
				// 		custom.tool.clearToken();
				// 		custom.tool.jump(2, 'login/login');
				// 	}
				// 	return false;
				// }

				if (res.data.code != 200) {

					// console.log(res)

					if (res.data.code == 401) {
						custom.tool.showToast(res.data.msg, true, 1200, 'none', '', function() {
							custom.tool.clearToken();
							custom.tool.jump(2, 'login/login');
						});

						return false;
					}
					if (res.data.code == 204) {
						custom.tool.showToast(res.data.msg, true, 1200, 'none', '', function() {
							custom.tool.jump(0, 'address/index');
						});
						return false;
					}
					if(res.data.code == 202){
						custom.tool.showToast(res.data.msg, true, 1200, 'none', '', function() {
							custom.tool.jump(0, 'my/walletManagement');
						});
						return false;
					
					}
					if(res.data.code == 201){
						custom.tool.showToast(res.data.msg, true, 1200, 'none', '', function() {
							custom.tool.jump(0, 'my/authentication');
						});
						return false;
					
					}
					if (res.data.code == 266) {
						uni.showModal({
							title: "提示",
							content: "" + res.data.msg,
							showCancel: true,
							cancelText: '不添加',
							confirmText: '添加',
							success: res => {
								if (res.confirm) {
									custom.tool.jump(0, 'address/index');
								} else {
									// 否则点击了取消  
								}
							}
						})
						return
					}
					if (res.data.code == 304) {
						
						var qq = res.data.data.contact_us_qq
						console.log(111,qq)
						uni.showModal({
							title: "提示",
							content: "" + res.data.msg+'\n'+qq,
							showCancel: true,
							cancelText: '取消',
							confirmText: '复制',
							success: res => {
								if (res.confirm) {
									custom.tool.setClipboardText(''+qq, {},{});
								} else {
									// 否则点击了取消  
								}
							}
						})
						return
					}
					// if(custom.tool.httpCodeLogin(res.data.code)){
					// 	custom.tool.clearToken();
					// 	// #ifdef H5
					// 		// window.location.reload();
					// 	// #endif
					// 	custom.tool.jump(2,'my/login');
					// }
					if (res.data.msg && typeof res.data.msg == 'string' && res.data.msg != '') {
						custom.tool.showToast(res.data.msg);
						if( (baseUrl + uri)== 'http://zygq.opo5.com/api/carshop/lists'){
							if (typeof callback == "function") {
								callback(res.data);
							}
						}
						return false
					}
					if (typeof callback == "function") {
						callback(res.data);
					}
					return false;
				}

				if (typeof callback == "function") {
					callback(res.data);
				}

			},
			fail: function(res) {
				console.log(res)
				custom.tool.hideLoading();
				// #ifdef H5
				// custom.tool.clearToken();
				// custom.tool.jump(2, 'login/login');
				// #endif
				// custom.tool.clearToken();
				// 
				// custom.tool.clearToken();
				// custom.tool.jump(2, 'login/login');
				if (typeof errorText == "string" && errorText != '') {
					custom.tool.showToast(errorText);
				}
			},
			complete: function() {
				uni.stopPullDownRefresh();
			}
		});
	});
}


/**
 * 封装请求
 */
function shop(flag) {
	let shopUri = !flag ? '' : 'shop/';
	return {
		get: function(uri, data, callback, errorText, isLoading) {
			isLoading = typeof isLoading != "boolean" ? true : isLoading;
			requests(shopUri + uri, data, callback, 'GET', errorText, isLoading);
			return this;
		},
		post: function(uri, data, callback, errorText, isLoading) {
			isLoading = typeof isLoading != "boolean" ? true : isLoading;
			requests(shopUri + uri, data, callback, 'POST', errorText, isLoading);
			return this;
		},
		put: function(uri, data, callback, errorText, isLoading) {
			isLoading = typeof isLoading != "boolean" ? true : isLoading;
			requests(shopUri + uri, data, callback, 'PUT', errorText, isLoading);
			return this;
		},
		delete: function(uri, data, callback, errorText, isLoading) {
			isLoading = typeof isLoading != "boolean" ? true : isLoading;
			requests(shopUri + uri, data, callback, 'DELETE', errorText, isLoading);
			return this;
		}
	}
}

/**
 * 封装上传
 * @param {Object} uri 上传地址
 * @param {Object} files 文件数组或单个文件
 * @param {Object} fileType 文件类型image/video/audio(默认image)
 * @param {Object} formData 附加数据
 * @param {Object} callback 回调函数
 * @param {Object} progress 进度回调函数
 */

function upload(files, data, callback) {

	getToken(function(token, time) {
		let isLogin = uni.getStorageSync('isLogin');
		isLogin = typeof isLogin == "undefined" || isLogin == null ? '' : isLogin;
		if (!token && isLogin) {
			custom.tool.jump(2, 'login/login');
			return
		}
		var key = '1062ce83a454d50e5d2c2a73c86fb978' + '@' + time
		const tempData = {}
		Object.keys(data).sort().map(item => {
			tempData[item] = data[item]
		})
		const newObj = []
		Object.keys(tempData).sort().map(item => {
			newObj.push(`${item}=${data[item]}`)
		})
		const signData = newObj.join('&')
		console.log(signData)
		console.log(key)
		var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
		hmac.update(signData);
		// const sha = CryptoJS.HmacSHA256(signData, key);
		// const sign = CryptoJS.createHmac('sha256', signData).update(key).digest('hex')
		// const sign = CryptoJS.enc.Hex.stringify(sha)
		// const sign1 = CryptoJS.enc.Base64.stringify(sha)
		const sign = CryptoJS.enc.Hex.stringify(hmac.finalize())
		// console.log(sign)
		// console.log(sign1)
		let header = {
			'token': token,
			'time': time,
			'sign': sign,
			// 'Content-Type': 'application/x-www-form-urlencoded'
		};
		// console.log(header)	
		// console.log(data)
		// console.log(baseUrl+uri)
		custom.tool.showLoading('正在上传');
		uni.uploadFile({
			url: uploadImage,
			filePath: files,
			name: 'file',
			formData: data,
			header: header,
			success: (res) => {
				custom.tool.hideLoading()
				if (res.statusCode == 200) {
					var res = JSON.parse(res.data)
					callback(res)

				} else {
					custom.tool.showToast('上传失败');
				}
			},
			fail: (err) => {
				custom.tool.hideLoading()
				console.log(err)
				custom.tool.showToast('上传失败');
			}
		});

	});

}


export default {
	baseUrl,
	domainAddress,
	shop,
	upload,
	isLogin,
	getToken,
	uploadImage,
	payUrl,
	requests
}